import { reqPhoneLogin } from "../../request/user"
import PubSub from "pubsub-js"

Page<DataModel, CustomOptionModel>({
  data: {
    phone: "",
    password: "",
  },

  handleInput(e) {
    this.setData({
      [e.target.dataset.type]: e.detail.value,
    })
  },

  async handleLogin() {
    const res = await reqPhoneLogin(this.data.phone, this.data.password)
    /*
      服务器返回的结果状态码:
          400 ->  手机号错误
          501 ->  账户不存在
          502 ->  密码错误
          200 ->  登录成功
    */
    const codeHandle: { [key: number]: WechatMiniprogram.ShowToastOption } = {
      200: { title: "登录成功", icon: "success" },
      400: { title: "手机号错误", icon: "error" },
      501: { title: "账户不存在", icon: "error" },
      502: { title: "密码错误", icon: "error" },
    }

    wx.showToast(codeHandle[res.code])
    if (res.code !== 200) return

    wx.setStorage({
      key: "uid",
      data: res.profile.userId,
    })

    PubSub.publish("setIds")

    wx.navigateBack()
  },
})

interface DataModel {
  phone: string
  password: string
}

interface CustomOptionModel {
  handleInput: (e: WechatMiniprogram.Input) => void
  handleLogin: () => void
}
